package com.hll.spring_book.service.borrow;

import com.hll.spring_book.mapper.borrow.BorrowMapper;
import com.hll.spring_book.pojo.Borrow;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * (Borrow)表服务实现类
 *
 * @author makejava
 * @since 2021-03-30 13:54:10
 */
@Service("borrowService")
public class BorrowServiceImpl implements BorrowService {
  @Resource private BorrowMapper borrowMapper;

  /**
   * 通过ID查询单条数据
   *
   * @param id 主键
   * @return 实例对象
   */
  @Override
  public Borrow queryById(Integer id) {
    return this.borrowMapper.queryById(id);
  }

  /**
   * 查询多条数据
   *
   * @return 对象列表
   */
  @Override
  public List<Borrow> queryAllByLimit(Borrow borrow) {
    return this.borrowMapper.queryAll(borrow);
  }

  /**
   * 新增数据
   *
   * @param borrow 实例对象
   * @return 实例对象
   */
  @Transactional(
      propagation = Propagation.REQUIRED,
      isolation = Isolation.DEFAULT,
      timeout = 36000,
      rollbackFor = Exception.class)
  @Override
  public Borrow insert(Borrow borrow) {
    this.borrowMapper.insert(borrow);
    return queryById(borrow.getId());
  }

  /**
   * 修改数据
   *
   * @param borrow 实例对象
   * @return 实例对象
   */
  @Transactional(
      propagation = Propagation.REQUIRED,
      isolation = Isolation.DEFAULT,
      timeout = 36000,
      rollbackFor = Exception.class)
  @Override
  public Borrow update(Borrow borrow) {
    this.borrowMapper.update(borrow);
    return this.queryById(borrow.getId());
  }

  /**
   * 通过主键删除数据
   *
   * @param id 主键
   * @return 是否成功
   */
  @Transactional(
      propagation = Propagation.REQUIRED,
      isolation = Isolation.DEFAULT,
      timeout = 36000,
      rollbackFor = Exception.class)
  @Override
  public boolean deleteById(Integer id) {
    return this.borrowMapper.deleteById(id) > 0;
  }

  @Override
  public boolean hasBorrowedBook(Integer userId, Integer bookId) {
    Borrow borrow = new Borrow();
    borrow.setStatus(false); // 未还，之前写成了true
    borrow.setUserId(userId);
    borrow.setBookId(bookId);
    return borrowMapper.queryAll(borrow).size() > 0;
  }
}
